package com.xiaoyushu.xiaoyushu.gateway.filer;

import cn.dev33.satoken.stp.StpUtil;
import com.xiaoyushu.framework.common.constant.GlobalConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order(-90)
public class AddUserId2HeaderFilter implements GlobalFilter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Header 头中Token 的key
     *
     */
    private static final String TOKEN_HEADER_TOKEN = "Authorization";

    /**
     * Token 前
     * 缀
     */
    private static final String TOKEN_HEADER_VALUE_PREFIX = "Bearer ";

    /**
     * 添加用户id
     */
    public static final String HEADER_USER_ID = "userId";
    /**
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==>gateway------ 过滤器TokenConvertFilter");
        //将请求传递给过滤器链中的下一个过滤器进行处理。如果堆请求进行任何修改。

        // 用户id
        Long userId=null;
        try {
            userId = StpUtil.getLoginIdAsLong();
        }catch (Exception e){
            //若没有登录，则直接放行
            return chain.filter(exchange);
        }
        log.info("当前登录用户 ID：{}",userId);
        Long finalUserId = userId;
        ServerWebExchange newExchange=exchange.mutate()
                .request(builder -> builder.header(GlobalConstants.USER_ID, String.valueOf(finalUserId)))
                .build();

        return chain.filter(newExchange);
    }
}
